home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / devel / lang / c / pthd-0.000 / pthd-0 / pthd-0.7 / src_thread / thread.c.4 < prev    next >
Encoding:
Text File  |  1995-08-16  |  1.9 KB  |  94 lines

  1. /*
  2.  * --  thread.c.4
  3.  *     Test of pthread_cond_timedwait()
  4.  */
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <dbgmem.h>
  8. #include <pthread.h>
  9. #include <signal.h>
  10. #include "utils.h"
  11.  
  12. static int safe = FALSE;
  13.  
  14. static pthread_t *th;
  15. static pthread_mutex_t mu;
  16. static pthread_cond_t cv;
  17.  
  18. static void 
  19. cv_timer( struct timespec *ts )
  20. {
  21.     int status, success = SUCCESS;
  22.  
  23.     status = pthread_mutex_lock( &mu );
  24.     CHECK(status, "pthread_mutex_lock()" );
  25.  
  26.     while( safe == FALSE )
  27.     {
  28.         status = pthread_cond_timedwait( &cv, &mu, ts );
  29.         CHECK( status, "pthread_cond_timedwait()" );
  30.     }
  31.  
  32.     status = pthread_mutex_unlock( &mu );
  33.     CHECK(status, "pthread_mutex_unlock()" );
  34.  
  35.     pthread_exit( (void *) success );
  36. }
  37.  
  38. int 
  39. main( int argc, char *argv[] )
  40. {
  41.     int i, st, exit_status, thread_count = 1;
  42.     struct timespec *tspec;
  43.  
  44.     if( argc == 2 )
  45.         thread_count = atoi( argv[1] );
  46.  
  47.     st = pthread_mutex_init( &mu, NULL );
  48.     CHECK( st, "pthread_mutex_init()");
  49.  
  50.     st = pthread_cond_init( &cv, NULL );
  51.     CHECK( st, "pthread_cond_init()");
  52.  
  53.     th = malloc_r( thread_count * sizeof( pthread_t ) );
  54.     tspec = malloc_r( thread_count * sizeof( struct timespec ) );
  55.  
  56.     for(i = 0; i < thread_count; i++ )
  57.     {
  58.         tspec[i].tv_sec = 1;
  59.         tspec[i].tv_nsec = rand() % 9999;
  60.  
  61.         st =  create_joinable( &th[i], (thread_proc_t) cv_timer, &tspec[i] );
  62.         CHECK( st, "create_joinable()");
  63.  
  64.         pthread_yield( NULL );
  65.     }
  66.  
  67.     safe = TRUE;
  68.  
  69.     for(i = 0; i < thread_count; i++ )
  70.     {
  71.         st = pthread_join( th[i], (void **) &exit_status );
  72.         CHECK( st, "pthread_join()");
  73.  
  74.         pthread_lock_global_np();
  75.         if( exit_status != SUCCESS )
  76.             fprintf( stderr, "Failed to join with th[%d]!", i);
  77.         else
  78.             printf("th[%d] complete!\n", i );
  79.         pthread_unlock_global_np();
  80.     }
  81.  
  82.     free_r( th );
  83.     free_r( tspec );
  84.  
  85.     st = pthread_cond_destroy( &cv );
  86.     CHECK( st, "pthread_cond_destroy()");
  87.  
  88.     st = pthread_mutex_destroy( &mu );
  89.     CHECK( st, "pthread_mutex_destroy()");
  90.  
  91.     print_system_counters();
  92.     return( EXIT_SUCCESS );
  93. }
  94.